package com.test.service.impl;

import com.test.service.IsolationTestService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class IsolationTestServiceImpl implements IsolationTestService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void readCommittedOperation() {
        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap("select * from test_table where id = 1");
        System.out.println("READ_COMMITTED: " + stringObjectMap.get("name"));
        // 模拟长时间操作
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Map<String, Object> stringObjectMap2 = jdbcTemplate.queryForMap("select * from test_table where id = 1");
        System.out.println("READ_COMMITTED: " + stringObjectMap2.get("name"));
    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public void repeatableReadOperation() {
        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap("select * from test_table where id = 1");
        System.out.println("REPEATABLE_READ: " + stringObjectMap.get("name"));
        // 模拟长时间操作
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Map<String, Object> stringObjectMap2 = jdbcTemplate.queryForMap("select * from test_table where id = 1");
        System.out.println("REPEATABLE_READ: " + stringObjectMap2.get("name"));
    }

    @Override
    @Transactional
    public void updateName(String name) {
        jdbcTemplate.update("update test_table set name = ? where id = 1", name);
    }
}
